<?php

/**
 * This is the model class for table "bln_circle".
 *
 * The followings are the available columns in table 'bln_circle':
 * @property integer $_id
 * @property string $circlename
 * @property string $profile
 */
class BCircle extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @return BCircle the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'bln_circle';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('circlename', 'required'),
            array('circlename', 'length', 'max' => 128),
            array('profile', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('_id, circlename, profile', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(            
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            '_id' => 'ID',
            'circlename' => 'Circlename',
            'profile' => 'Profile',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('_id', $this->_id);
        $criteria->compare('circlename', $this->circlename, true);
        $criteria->compare('profile', $this->profile, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }   

    public static function findRecursivedParentsById($circleId) {
        $circles = array();

        $circle = BCircle::model()->findByPk($circleId);

        while ($circle = $circle->parentCircle) {
            $circles[$circle->_id] = $circle;
        }

        if (!empty($circles))
            return $circles;

        return false;
    }

    public static function findRecursiveChildren($circle, $circles) {
        $childrenCircles = array();
        while ($childrenCircles = $circle->ChildrenCircles) {
            array_merge($circles, $childrenCircles);
            foreach ($childrenCircles as $circle) {
                $this->findRecursiveChildren($circle, $circles);
            }
        }
    }

    protected static function findChildrenById($circleId) {
        $rows = $this->db->createCommand()
                        ->select()
                        ->from($this->circleChildTable)
                        ->where('parentcircleid=:parentid', array(':parentid' => $circleId))
                        ->queryAll();
        $childrenCircles = array();
        if ($rows->rowCount <= 0) {
            return false;
        } else {
            foreach ($rows as $row) {
                $childrenCircles[$row['_id']] = BCircle::model()->findByPk($row['childcircleid']);
            }
            return $childrenCircles;
        }
    }

    protected static function findUsersById($circleId) {
        $rows = $this->db->createCommand()
                        ->select()
                        ->from($this->circleUserTable)
                        ->where('circle_id=:circleid', array(':circleid' => $circleId))
                        ->queryAll();
        $users = array();
        foreach ($rows as $row) {
            $user = BUser::model()->findByPk($row['user_id']);
            $users[$user->_id] = $user;
        }
        return $users;
    }

    public static function findParentById($circleId) {
        $row = $this->db->createCommand()
                        ->select()
                        ->from($this->circleChildTable)
                        ->where('childcircleid=:childid', array(':childid' => $circleId))
                        ->queryRow();

        if ($row != false) {
            $circle = BCircle::model()->findByPk($row['parentcircleid']);
            return $circle;
        }
        return false;
    }

    public function getParent() {
        return $this->findParentById($this->_id);
    }

    public function getChildren() {
        return $this->findChildrenById($this->_id);
    }

    public function getRecursiveParents() {
        return $this->findRecursiveParentsById($this->_id);
    }

    public function getRecursiveChildren() {
        $circles = array();
        $this->findRecursiveChildren($this, $circles);

        if (!empty($circles))
            return $circles;

        return false;
    }

    public function getUsers() {
        return $this->findUsersById($this->_id);
    }

    public function getRecursiveUsers() {
        $users = $this->getCircleUsers();

        $circles = $this->getRecursiveChildren();

        foreach ($circles as $circle) {
            array_merge($users, $circle->Users);
        }

        return $users;
    }

}

